import React, { useState } from 'react';
import { Layout, Menu, theme } from 'antd';
import {
  DashboardOutlined,
  ShoppingOutlined,
  ShoppingCartOutlined,
  UserOutlined,
  TeamOutlined,
  SafetyOutlined,
  AppstoreOutlined,
  CustomerServiceOutlined,
  FileTextOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined
} from '@ant-design/icons';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { useAdminAuth } from '../../hooks/useAuth';
import AdminHeader from './Header';
import './Layout.css';

const { Sider, Content } = Layout;

const AdminLayout = () => {
  const [collapsed, setCollapsed] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const { hasAdminPermission } = useAdminAuth();
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  // 获取当前选中的菜单项
  const getSelectedKey = () => {
    const path = location.pathname;
    if (path === '/admin') return 'dashboard';
    const key = path.split('/').pop();
    return key;
  };

  // 菜单配置
  const menuItems = [
    {
      key: 'dashboard',
      icon: <DashboardOutlined />,
      label: '仪表板',
      path: '/admin',
      permission: null // 所有人都可以访问
    },
    {
      key: 'product-group',
      icon: <ShoppingOutlined />,
      label: '商品管理',
      children: [
        {
          key: 'products',
          label: '商品列表',
          path: '/admin/products',
          permission: 'product:view'
        },
        {
          key: 'categories',
          label: '分类管理',
          path: '/admin/categories',
          permission: 'category:view'
        }
      ]
    },
    {
      key: 'order-group',
      icon: <ShoppingCartOutlined />,
      label: '订单管理',
      children: [
        {
          key: 'orders',
          label: '订单列表',
          path: '/admin/orders',
          permission: 'order:view'
        },
        // {
        //   key: 'refunds',
        //   label: '售后管理000',
        //   path: '/admin/refunds',
        //   permission: 'refund:view'
        // },
        {
          key: 'after-sales',
          label: '售后管理',
          path: '/admin/after-sales',
          permission: 'refund:view'
        }
      ]
    },
    {
      key: 'user-group',
      icon: <UserOutlined />,
      label: '用户管理',
      children: [
        {
          key: 'users',
          label: '前台用户',
          path: '/admin/users',
          permission: 'user:view'
        },
        {
          key: 'admin-users',
          label: '管理员',
          path: '/admin/admin-users',
          permission: 'admin:view'
        }
      ]
    },
    {
      key: 'permission-group',
      icon: <SafetyOutlined />,
      label: '权限管理',
      children: [
        {
          key: 'roles',
          label: '角色权限',
          path: '/admin/roles',
          permission: 'role:view'
        }
      ]
    },
    {
      key: 'system-group',
      icon: <AppstoreOutlined />,
      label: '系统管理',
      children: [
        {
          key: 'logs',
          label: '操作日志',
          path: '/admin/logs',
          permission: 'log:view'
        }
      ]
    }
  ];

  // 过滤有权限的菜单项
  const filterMenuItems = (items) => {
    return items.filter(item => {
      // 如果没有权限要求，或者有权限，则显示
      if (!item.permission || hasAdminPermission(item.permission)) {
        // 如果有子菜单，递归过滤
        if (item.children) {
          const filteredChildren = filterMenuItems(item.children);
          if (filteredChildren.length > 0) {
            return { ...item, children: filteredChildren };
          }
          return false;
        }
        return true;
      }
      return false;
    }).map(item => {
      if (item.children) {
        const filteredChildren = filterMenuItems(item.children);
        return { ...item, children: filteredChildren };
      }
      return item;
    });
  };

  const handleMenuClick = ({ key }) => {
    // 查找对应的路径
    const findPath = (items) => {
      for (const item of items) {
        if (item.key === key && item.path) {
          return item.path;
        }
        if (item.children) {
          const path = findPath(item.children);
          if (path) return path;
        }
      }
      return null;
    };

    const path = findPath(menuItems);
    if (path) {
      navigate(path);
    }
  };

  return (
    <Layout className="admin-layout">
      <Sider 
        trigger={null} 
        collapsible 
        collapsed={collapsed}
        className="admin-sider"
        width={220}
      >
        <div className="admin-logo">
          <ShoppingCartOutlined className="logo-icon" />
          {!collapsed && <span className="logo-text">商城管理系统</span>}
        </div>
        
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={[getSelectedKey()]}
          defaultOpenKeys={['product-group', 'order-group', 'user-group']}
          items={filterMenuItems(menuItems)}
          onClick={handleMenuClick}
          className="admin-menu"
        />
        
        <div className="sider-trigger" onClick={() => setCollapsed(!collapsed)}>
          {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        </div>
      </Sider>
      
      <Layout>
        <AdminHeader />
        
        <Content className="admin-content">
          <div className="content-wrapper">
            <Outlet />
          </div>
        </Content>
      </Layout>
    </Layout>
  );
};

export default AdminLayout;